﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Topro.Application.Impl
{
    using Dapper;
    using Dapper.Contrib.Extensions;
    using Topro.Application.Interface;
    using Topro.Db;
    using Topro.Entity;
    using Topro.Entity.Enum;
    using Topro.Entity.Query;
    using Topro.Entity.Request.Info;
    using Topro.Entity.Response.Info;
    using Topro.Entity.Tables;
    using Topro.Log;

    /// <summary>
    /// 日志
    /// </summary>
    public class InfoServiceImpl : InfoService
    {
        #region 注入
        /// <summary>
        /// db
        /// </summary>
        private readonly IDb _db;

        /// <summary>
        /// loggerService
        /// </summary>
        private readonly LoggerService _loggerService;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="dapperFactory"></param>
        /// <param name="logger"></param>
        public InfoServiceImpl(IDb db, LoggerService loggerService)
        {
            _db = db;
            _loggerService = loggerService;
        }
        #endregion

        /// <summary>
        /// 获取
        /// </summary>
        /// <param name="id">编号</param>
        /// <returns></returns>
        public InfoResponse GetInfo(int id)
        {
            var info = _db.DbConnection.QueryFirst<InfoResponse>("select * from info where Id=@Id", new { Id = id });
            if (info != null)
            {
                return info;
            }
            return null;
        }

        /// <summary>
        /// 保存、修改
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public JResult Save(SaveInfoRequest request)
        {
            var response = new JResult()
            {
                Success = false
            };

            if (request.Id > 0)
            {
                var info = _db.DbConnection.QueryFirst<Info>("select * from info where Id=@Id", new { Id = request.Id });
                if (info == null)
                {
                    throw new Exception("消息记录不存在.");
                }

                info.Type = request.Type.Value;
                info.Value = request.Value;
                info.Message = request.Message;
                //更新
                _db.DbConnection.Update<Info>(info);

                response.Success = true;
            }
            else
            {

                var info = new Info()
                {
                    Type = request.Type.Value,
                    Value = request.Value,
                    Message = request.Message,
                    Record = "0",
                    Status = (int)InfoStatus.启用,
                    CreatedDate = DateTime.Now
                };

                //新增
                var resultId = _db.DbConnection.Insert<Info>(info);
                if (resultId <= 0)
                {
                    throw new Exception("新增失败.");
                }
                response.Success = true;
            }
            return response;
        }

        /// <summary>
        /// 更新状态
        /// </summary>
        /// <returns></returns>
        public JResult UpdateUserStatus(int id, int status)
        {
            var response = new JResult()
            {
                Success = false
            };

            try
            {
                var info = _db.DbConnection.QueryFirst<Info>("select * from info where Id=@Id", new { Id = id });
                if (info == null)
                {
                    throw new Exception("记录不存在.");
                }

                var updateSql = "UPDATE info SET Status=@Status WHERE Id=@Id";

                int result = _db.DbConnection.Execute(updateSql, new { Status = status, Id = id });
                if (result <= 0)
                {
                    throw new Exception("更新失败");
                }
                response.Success = true;
                response.Message = "操作成功.";
            }
            catch (Exception ex)
            {
                response.Message = ex.Message;
            }

            return response;
        }

        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public PagedList<InfoQueryResponse> GetPager(InfoQuery query)
        {
            var pageIndex = query.PageIndex <= 0 ? 0 : (query.PageIndex - 1) * query.PageSize;

            var files = "i.*";
            var tableName = "info i";
            var orderby = "ORDER BY i.Id DESC";
            var where = "where 1=1";

            #region 条件
            //类型
            if (query.Type.HasValue)
            {
                where += string.Format(" And i.Type ={0}", query.Type.Value);
            }
            //批号
            if (!string.IsNullOrEmpty(query.Value))
            {
                where += string.Format(" And i.Value like '%{0}%'", query.Value);
            }
            #endregion

            var sb = new StringBuilder();

            sb.AppendFormat("SELECT COUNT(1) FROM {0} {1};", tableName, where);
            sb.AppendFormat("SELECT {0} FROM {1} {2} {3} LIMIT {4},{5};", files, tableName, where, orderby, pageIndex, query.PageSize);
            using (var multi = _db.DbConnection.QueryMultiple(sb.ToString()))
            {
                var count = multi.ReadFirst<int>();

                var list = multi.Read<InfoQueryResponse>();

                return new PagedList<InfoQueryResponse>()
                {
                    TData = list,
                    CurrentPageIndex = query.PageIndex,
                    TotalCount = count
                };
            }
        }
    }
}
